package com.example.demo.service.impl;

import com.example.demo.service.ProcessService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.flowable.bpmn.model.*;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProcessServiceImpl implements ProcessService {

    private  final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    RepositoryService repositoryService;

    /**
     * 启动请假申请流程
     */
    @Override
    public String startLeaveRequest(String employee, String reason, int days) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("employee", employee);
        variables.put("reason", reason);
        variables.put("days", days);

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leaveRequest", variables);
        return processInstance.getId();

    }

    /**
     * 获取用户的任务列表
     */
    @Override
    public List<Task> getUserTasks(String assignee) {
        return taskService.createTaskQuery()
                .taskAssignee(assignee)
                .list();
    }

    /**
     * 获取候选组的任务列表
     */
    @Override
    public List<Task> getGroupTasks(String group) {
        return taskService.createTaskQuery()
                .taskCandidateGroup(group)
                .list();
    }

    /**
     * 完成任务
     */
    @Override
    public void completeTask(String taskId, Map<String, Object> variables) {
        taskService.complete(taskId, variables);
    }

    /**
     * 获取任务详情
     */
    @Override
    public Task getTask(String taskId) {
        return taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();
    }


        /**
         * 获取任务的扩展属性
         *
         * @param taskId 任务ID
         * @return 扩展属性Map
         * @author 您的姓名
         * @date 2025/01/14 17:29
         */
        public List<ExtensionElement>  getTaskExtensionProperties(String taskId) {
            Task task = taskService.createTaskQuery()
                    .taskId(taskId)
                    .singleResult();

            List<ExtensionElement> values = null;

            if (task != null) {
                String processDefinitionId = task.getProcessDefinitionId();
                BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);

                // 根据任务定义Key获取对应的流程元素
                FlowElement flowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey());

                if (flowElement instanceof UserTask) {
                    UserTask userTask = (UserTask) flowElement;

                    // ✅ 正确获取 ExtensionElements
                    Map<String, List<ExtensionElement>> extensionElements = userTask.getExtensionElements();

                    if (extensionElements != null) {
                        // 获取所有子元素名为 customProperties 的扩展元素
                        values = extensionElements.get("customProperties");
                        List<org.flowable.bpmn.model.ExtensionElement> customPropsElements =
                                values.stream()
                                        .filter(el -> "customProperty".equals(el.getName()))
                                        .collect(Collectors.toList());


                        for (org.flowable.bpmn.model.ExtensionElement prop : values) {
                            String name = prop.getAttributeValue(null, "name");
                            String value = prop.getAttributeValue(null, "value");
                            System.out.println("自定义属性 - name: " + name + ", value: " + value);
                        }
                    } else {
                        System.out.println("该 UserTask 没有定义 ExtensionElements");
                    }
                } else {
                    System.out.println("该流程元素不是 UserTask");
                }
            }

            return values;

        }

            /**
             * 解析 ruleJson 配置
             *
             * @param ruleJson JSON字符串
             * @return 解析后的规则对象
             * @author 您的姓名
             * @date 2025/01/14 17:29
             */
//        public RuleConfig parseRuleJson(String ruleJson) {
//            try {
//                ObjectMapper mapper = new ObjectMapper();
//                return mapper.readValue(ruleJson, RuleConfig.class);
//            } catch (Exception e) {
//                logger.error("解析ruleJson失败: {}", ruleJson, e);
//                return null;
//            }
//        }

}
